﻿@model Entity.SysOrgUserManagement
@{
    ViewData["Title"] = "个人中心";
    // 提前判断性别单选框的选中状态
    bool isMaleChecked = Model != null && Model.Sex == "男";
    bool isFemaleChecked = Model != null && Model.Sex == "女";
}

<style>
    :root {
        --primary-color: #3498db;
        --success-color: #2ecc71;
        --danger-color: #e74c3c;
        --light-bg: #f8f9fa;
        --border-color: #e9ecef;
        --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    body {
        background-color: #f5f7fa;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        color: #333;
    }

    .profile-container {
        max-width: 1000px;
        margin: 30px auto;
        padding: 0 15px;
    }

    .profile-card {
        background: white;
        border-radius: 12px;
        box-shadow: var(--shadow);
        overflow: hidden;
    }

    .nav-tabs {
        background-color: var(--light-bg);
        padding: 0 20px;
        border-bottom: 1px solid var(--border-color);
    }

        .nav-tabs .nav-link {
            border: none;
            padding: 15px 25px;
            font-weight: 500;
            color: #6c757d;
            border-radius: 0;
            position: relative;
        }

            .nav-tabs .nav-link.active {
                color: var(--primary-color);
                background: transparent;
                border-bottom: 3px solid var(--primary-color);
            }

            .nav-tabs .nav-link:hover {
                border: none;
                color: var(--primary-color);
            }

    .tab-content {
        padding: 30px;
    }

    .profile-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 25px;
        padding-bottom: 20px;
        border-bottom: 1px solid var(--border-color);
    }

    .avatar-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 150px;
    }

    .avatar-img {
        width: 120px;
        height: 120px;
        object-fit: cover;
        border-radius: 50%;
        border: 4px solid var(--primary-color);
        box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        transition: all 0.3s ease;
        cursor: pointer;
    }

        .avatar-img:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 15px rgba(52, 152, 219, 0.4);
        }

    .avatar-actions {
        margin-top: 15px;
        text-align: center;
    }

    .avatar-preview-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 1050;
    }

    .avatar-preview-content {
        background: white;
        padding: 20px;
        border-radius: 12px;
        text-align: center;
        max-width: 400px;
        width: 90%;
    }

    .avatar-preview-img {
        width: 200px;
        height: 200px;
        object-fit: cover;
        border-radius: 50%;
        margin-bottom: 20px;
        border: 4px solid var(--primary-color);
    }

    .avatar-preview-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
    }

    .form-section {
        flex: 1;
        padding-right: 30px;
    }

    .form-label {
        font-weight: 600;
        color: #495057;
    }

    .form-control, .form-select {
        border-radius: 8px;
        padding: 10px 15px;
        border: 1px solid var(--border-color);
        transition: all 0.3s;
    }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }

        .form-control[readonly] {
            background-color: #f8f9fa;
            color: #6c757d;
        }

    .btn-success {
        background-color: var(--success-color);
        border: none;
        border-radius: 8px;
        padding: 10px 25px;
        font-weight: 500;
        transition: all 0.3s;
    }

        .btn-success:hover {
            background-color: #27ae60;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(46, 204, 113, 0.3);
        }

    .btn-outline-secondary {
        border-radius: 8px;
        padding: 10px 25px;
        font-weight: 500;
    }

    .gender-options {
        display: flex;
        gap: 20px;
        margin-top: 8px;
    }

    .gender-option {
        display: flex;
        align-items: center;
        cursor: pointer;
    }

        .gender-option input {
            margin-right: 8px;
        }

    .alert-message {
        border-radius: 8px;
        padding: 12px 15px;
        margin-bottom: 20px;
        transition: all 0.3s ease;
    }

    .loading {
        opacity: 0.6;
        pointer-events: none;
    }

    .spinner-border-sm {
        width: 1rem;
        height: 1rem;
    }

    .file-input-wrapper {
        position: relative;
        display: inline-block;
    }

    .avatar-upload-progress {
        margin-top: 10px;
        display: none;
    }

    .progress-bar {
        transition: width 0.3s ease;
    }

    .form-submit-loading {
        position: relative;
        pointer-events: none;
    }

        .form-submit-loading .btn-text {
            visibility: hidden;
        }

        .form-submit-loading .spinner-border {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

    /* 新增：密码验证提示样式 */
    .password-hint {
        font-size: 0.875rem;
        color: #6c757d;
        margin-top: 4px;
    }

    .password-mismatch {
        color: var(--danger-color);
        font-size: 0.875rem;
        margin-top: 4px;
        display: none;
    }

    @@media (max-width: 768px) {
        .profile-header {
            flex-direction: column-reverse;
        }

        .avatar-section {
            width: 100%;
            margin-bottom: 20px;
            flex-direction: row;
            justify-content: center;
        }

        .avatar-actions {
            margin-top: 0;
            margin-left: 15px;
        }

        .form-section {
            padding-right: 0;
        }
    }
</style>

<div class="profile-container">
    <div class="profile-card">
        <!-- 选项卡导航 -->
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="true">
                    <i class="fas fa-user me-2"></i>个人资料
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password" type="button" role="tab" aria-controls="password" aria-selected="false">
                    <i class="fas fa-key me-2"></i>修改密码
                </button>
            </li>
        </ul>

        <!-- 选项卡内容 -->
        <div class="tab-content" id="myTabContent">
            <!-- 个人资料面板 -->
            <div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                <div class="profile-header">
                    <div class="form-section">
                        <h3 class="mb-4"><i class="fas fa-id-card me-2"></i>个人资料</h3>

                        <!-- 消息提示：显示后立即清除，避免残留 -->
                        @if (TempData["Message"] != null)
                        {
                            <div class="alert alert-success alert-message">
                                <i class="fas fa-check-circle me-2"></i>@TempData["Message"]
                            </div>
                            TempData.Remove("Message");
                        }
                        @if (TempData["Error"] != null)
                        {
                            <div class="alert alert-danger alert-message">
                                <i class="fas fa-exclamation-circle me-2"></i>@TempData["Error"]
                            </div>
                            TempData.Remove("Error");
                        }

                        <form asp-action="SaveProfile" method="post" id="profileForm" enctype="multipart/form-data">
                            <input type="hidden" asp-for="UserId" />
                            <input type="hidden" asp-for="UserAccount" />
                            <input type="hidden" asp-for="UserAvatar" id="userAvatarInput" value="@Model?.UserAvatar" />
                            <input type="file" name="avatarFile" id="avatarFileInput" accept="image/*" style="display: none;" />

                            <!-- 用户账号 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">用户账号</label>
                                <div class="col-sm-9">
                                    <input asp-for="UserAccount" class="form-control" readonly>
                                </div>
                            </div>

                            <!-- 用户姓名 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">用户姓名 <span class="text-danger">*</span></label>
                                <div class="col-sm-9">
                                    <input asp-for="UserName" class="form-control" required>
                                    <span asp-validation-for="UserName" class="text-danger"></span>
                                </div>
                            </div>

                            <!-- 岗位名称 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">岗位名称</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control"
                                           value="@(Model?.JobName ?? "未设置岗位")" readonly>
                                </div>
                            </div>

                            <!-- 所在部门 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">所在部门</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control"
                                           value="@(Model?.DepartmentName ?? "未设置部门")" readonly>
                                </div>
                            </div>

                            <!-- 性别 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">性别</label>
                                <div class="col-sm-9">
                                    <div class="gender-options">
                                        <div class="gender-option">
                                            <input class="form-check-input" type="radio" asp-for="Sex" value="男" id="male" @@(isMaleChecked ? "checked" : "")>
                                            <label class="form-check-label" for="male">男</label>
                                        </div>
                                        <div class="gender-option">
                                            <input class="form-check-input" type="radio" asp-for="Sex" value="女" id="female" @@(isFemaleChecked ? "checked" : "")>
                                            <label class="form-check-label" for="female">女</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 手机号 -->
                            <div class="row mb-4">
                                <label class="col-sm-3 col-form-label form-label">手机号</label>
                                <div class="col-sm-9">
                                    <input asp-for="PhoneNumber" class="form-control" placeholder="请输入手机号">
                                    <span asp-validation-for="PhoneNumber" class="text-danger"></span>
                                </div>
                            </div>

                            <!-- 保存/重置按钮 -->
                            <div class="row mt-5">
                                <div class="col-sm-9 offset-sm-3">
                                    <button type="submit" class="btn btn-success me-3" id="saveProfileBtn">
                                        <span class="btn-text">
                                            <i class="fas fa-save me-2"></i>保存
                                        </span>
                                        <div class="spinner-border spinner-border-sm text-light d-none" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" id="resetFormBtn">
                                        <i class="fas fa-undo me-2"></i>重置
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="avatar-section">
                        @{
                            var avatarUrl = !string.IsNullOrEmpty(Model?.UserAvatar)
                            ? Model.UserAvatar
                            : "/images/default-avatar.png";
                        }
                        <img src="@avatarUrl" alt="用户头像" class="avatar-img" id="userAvatar" data-original-src="@avatarUrl">
                        <div class="avatar-actions">
                            <div class="file-input-wrapper">
                                <button type="button" class="btn btn-outline-primary btn-sm mt-2" id="changeAvatarBtn">
                                    <i class="fas fa-camera me-1"></i>更换头像
                                </button>
                            </div>
                            <div class="avatar-upload-progress" id="avatarUploadProgress">
                                <div class="progress" style="height: 6px;">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                                </div>
                                <small class="text-muted">上传中...</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 修改密码面板 -->
            <div class="tab-pane fade" id="password" role="tabpanel" aria-labelledby="password-tab">
                <h3 class="mb-4"><i class="fas fa-key me-2"></i>修改密码</h3>

                <!-- 消息提示：显示后立即清除，避免残留（仅保留一次判断） -->
                @if (TempData["Message"] != null)
                {
                    <div class="alert alert-success alert-message">
                        <i class="fas fa-check-circle me-2"></i>@TempData["Message"]
                    </div>
                    TempData.Remove("Message");
                }
                @if (TempData["Error"] != null)
                {
                    <div class="alert alert-danger alert-message">
                        <i class="fas fa-exclamation-circle me-2"></i>@TempData["Error"]
                    </div>
                    TempData.Remove("Error");
                }

                <form asp-action="DoChangePassword" method="post" id="passwordForm">
                    <div class="row mb-4">
                        <label class="col-sm-3 col-form-label form-label">原密码 <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="password" name="oldPassword" class="form-control" required placeholder="请输入原密码">
                        </div>
                    </div>

                    <div class="row mb-4">
                        <label class="col-sm-3 col-form-label form-label">新密码 <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="password" name="newPassword" id="newPassword" class="form-control" minlength="6" required placeholder="至少6位字符">
                            <div class="password-hint">提示：新密码不能与原密码一致</div>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <label class="col-sm-3 col-form-label form-label">确认新密码 <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="password" name="confirmNewPassword" id="confirmNewPassword" class="form-control" required placeholder="请再次输入新密码">
                            <div class="password-mismatch" id="passwordMismatchHint">
                                <i class="fas fa-exclamation-circle me-1"></i>新密码与确认密码不一致
                            </div>
                        </div>
                    </div>

                    <div class="row mt-5">
                        <div class="col-sm-9 offset-sm-3">
                            <button type="submit" class="btn btn-success me-3" id="savePasswordBtn">
                                <span class="btn-text">
                                    <i class="fas fa-save me-2"></i>保存
                                </span>
                                <div class="spinner-border spinner-border-sm text-light d-none" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </button>
                            <button type="reset" class="btn btn-outline-secondary" id="resetPasswordBtn">
                                <i class="fas fa-undo me-2"></i>重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 头像预览模态框 -->
<div class="avatar-preview-container" id="avatarPreviewModal">
    <div class="avatar-preview-content">
        <img src="" alt="头像预览" class="avatar-preview-img" id="avatarPreviewImg">
        <div class="avatar-preview-actions">
            <button type="button" class="btn btn-success" id="confirmAvatarBtn">
                <i class="fas fa-check me-1"></i>确认使用
            </button>
            <button type="button" class="btn btn-outline-secondary" id="cancelAvatarBtn">
                <i class="fas fa-times me-1"></i>取消
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 存储原始数据用于重置
    let originalData = {
        userName: '@Html.Raw(Model?.UserName ?? "")',
        phoneNumber: '@Html.Raw(Model?.PhoneNumber ?? "")',
        sex: '@Html.Raw(Model?.Sex ?? "")',
        userAvatar: '@Html.Raw(Model?.UserAvatar ?? "")'
    };

    // 页面加载完成
    document.addEventListener('DOMContentLoaded', function() {
        // 1. 性别选中状态（优化空值处理）
        if (originalData.sex === '男') {
            document.getElementById('male').checked = true;
        } else if (originalData.sex === '女') {
            document.getElementById('female').checked = true;
        }

        // 2. 密码实时验证（新密码与确认密码一致性）
        const newPwdInput = document.getElementById('newPassword');
        const confirmPwdInput = document.getElementById('confirmNewPassword');
        const mismatchHint = document.getElementById('passwordMismatchHint');
        const savePwdBtn = document.getElementById('savePasswordBtn');

        // 监听输入变化
        function checkPasswordMatch() {
            if (newPwdInput.value && confirmPwdInput.value) {
                if (newPwdInput.value !== confirmPwdInput.value) {
                    mismatchHint.style.display = 'block';
                    savePwdBtn.disabled = true;
                } else {
                    mismatchHint.style.display = 'none';
                    savePwdBtn.disabled = false;
                }
            } else {
                mismatchHint.style.display = 'none';
                savePwdBtn.disabled = false;
            }
        }

        newPwdInput.addEventListener('input', checkPasswordMatch);
        confirmPwdInput.addEventListener('input', checkPasswordMatch);

        // 3. 密码表单提交加载状态
        document.getElementById('passwordForm').addEventListener('submit', function(e) {
            savePwdBtn.classList.add('form-submit-loading');
            savePwdBtn.querySelector('.spinner-border').classList.remove('d-none');
        });
    });

    // 头像相关功能
    let selectedAvatarFile = null;

    // 点击更换头像
    document.getElementById('changeAvatarBtn').addEventListener('click', function() {
        document.getElementById('avatarFileInput').click();
    });

    // 选择头像文件
    document.getElementById('avatarFileInput').addEventListener('change', function(e) {
        if (this.files.length === 0) return;
        const file = this.files[0];

        // 验证文件类型和大小
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        const maxSize = 2 * 1024 * 1024; // 2MB

        if (!allowedTypes.includes(file.type)) {
            alert('请选择jpg、jpeg、png或gif格式的图片！');
            this.value = '';
            return;
        }

        if (file.size > maxSize) {
            alert('图片大小不能超过2MB！');
            this.value = '';
            return;
        }

        // 预览头像
        selectedAvatarFile = file;
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreviewImg').src = e.target.result;
            document.getElementById('avatarPreviewModal').style.display = 'flex';
        };
        reader.readAsDataURL(file);
    });

    // 密码可见切换（修复：原代码中"showOldPwdBtn"元素不存在，此处注释掉避免报错）
    // document.getElementById('showOldPwdBtn').addEventListener('click', function() { ... });

    // 确认使用头像
    document.getElementById('confirmAvatarBtn').addEventListener('click', function() {
        if (!selectedAvatarFile) return;
        // 更新预览
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('userAvatar').src = e.target.result;
        };
        reader.readAsDataURL(selectedAvatarFile);

        // 隐藏模态框
        document.getElementById('avatarPreviewModal').style.display = 'none';

        // 显示上传进度（模拟）
        const progressContainer = document.getElementById('avatarUploadProgress');
        const progressBar = progressContainer.querySelector('.progress-bar');
        progressContainer.style.display = 'block';
        
        let progress = 0;
        const interval = setInterval(() => {
            progress += 10;
            progressBar.style.width = `${progress}%`;
            if (progress >= 100) {
                clearInterval(interval);
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                    progressBar.style.width = '0%';
                }, 500);
            }
        }, 100);
    });

    // 取消头像选择
    document.getElementById('cancelAvatarBtn').addEventListener('click', function() {
        document.getElementById('avatarPreviewModal').style.display = 'none';
        document.getElementById('avatarFileInput').value = '';
        selectedAvatarFile = null;
    });

    // 点击头像预览大图
    document.getElementById('userAvatar').addEventListener('click', function() {
        const previewImg = document.getElementById('avatarPreviewImg');
        previewImg.src = this.src;
        document.getElementById('avatarPreviewModal').style.display = 'flex';
        document.getElementById('confirmAvatarBtn').style.display = 'none';
        document.getElementById('cancelAvatarBtn').textContent = '关闭';
    });

    // 点击模态框背景关闭
    document.getElementById('avatarPreviewModal').addEventListener('click', function(e) {
        if (e.target === this) {
            this.style.display = 'none';
            document.getElementById('confirmAvatarBtn').style.display = 'inline-block';
            document.getElementById('cancelAvatarBtn').textContent = '取消';
        }
    });

    // 个人资料表单提交加载状态
    document.getElementById('profileForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const submitBtn = document.getElementById('saveProfileBtn');
        submitBtn.classList.add('form-submit-loading');
        submitBtn.querySelector('.spinner-border').classList.remove('d-none');

        // 传递头像文件
        if (selectedAvatarFile) {
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(selectedAvatarFile);
            document.getElementById('avatarFileInput').files = dataTransfer.files;
        }

        // 提交表单
        this.submit();
    });

    // 重置个人资料表单
    document.getElementById('resetFormBtn').addEventListener('click', function() {
        // 重置字段
        document.getElementById('UserName').value = originalData.userName;
        document.getElementById('PhoneNumber').value = originalData.phoneNumber;

        // 重置性别
        if (originalData.sex === '男') {
            document.getElementById('male').checked = true;
            document.getElementById('female').checked = false;
        } else if (originalData.sex === '女') {
            document.getElementById('female').checked = true;
            document.getElementById('male').checked = false;
        } else {
            document.getElementById('male').checked = false;
            document.getElementById('female').checked = false;
        }

        // 重置头像
        document.getElementById('userAvatar').src = originalData.userAvatar || '/images/default-avatar.png';
        document.getElementById('avatarFileInput').value = '';
        selectedAvatarFile = null;

        // 清除验证状态
        document.getElementById('profileForm').classList.remove('was-validated');
    });

    // 表单验证（Bootstrap原生验证）
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!this.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            }
            this.classList.add('was-validated');
        });
    });

    // 自动隐藏消息提示
    setTimeout(() => {
        document.querySelectorAll('.alert-message').forEach(alert => {
            alert.style.opacity = '0';
            setTimeout(() => alert.style.display = 'none', 300);
        });
    }, 2500);
</script>